package cn.yunyichina.provider.base.service.impl;


import java.util.*;

import cn.yunyichina.provider.base.dao.*;
import cn.yunyichina.provider.base.entity.BranchHospital;
import cn.yunyichina.provider.base.entity.OrgAppDevelop;
import cn.yunyichina.provider.base.utils.CacheConstant;
import cn.yunyichina.provider.base.utils.ListUtils;
import cn.yunyichina.provider.framework.common.PKGenerator;
import cn.yunyichina.provider.framework.dubbo.service.BaseService;
import cn.yunyichina.provider.framework.utils.UUIDUtil;
import cn.yunyichina.provider.iface.entity.base.BranchOutVo;
import cn.yunyichina.provider.iface.entity.base.HospitalOutVo;
import cn.yunyichina.provider.iface.entity.base.Org;
import cn.yunyichina.provider.iface.entity.base.OrgApp;
import cn.yunyichina.utils.convert.ObjectParser;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;

import cn.yunyichina.provider.base.entity.Department;
import cn.yunyichina.provider.base.entity.HospitalPaySetting;
import cn.yunyichina.provider.framework.dubbo.service.CacheService;
import cn.yunyichina.provider.framework.page.PageInfo;
import cn.yunyichina.provider.iface.entity.HospitalCodeAndAppVo;
import cn.yunyichina.provider.iface.entity.HospitalPlatformRelate;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.utils.convert.JsonUtils;
import org.springframework.util.CollectionUtils;

@Service("hospitalServiceImpl")
public class HospitalServiceImpl {

    @Autowired
    private HospitalDao hospitalDao;

    @Autowired
    private DepartmentDao departmentDao;
    
    @Autowired
    private HospitalPlatformRelateDao hospitalPlatformRelateDao;

    @Autowired
    private OrgAppDevelopDao orgAppDevelopDao;

    @Autowired
    private OrgDao orgDao;

    @Autowired
    private BranchHospitalDao branchHospitalDao;

    private static Logger logger = LoggerFactory.getLogger(HospitalServiceImpl.class);

    /**
     * 医院列表
     */
    public Response listHospital(String data) {

        Response response = new Response();
        Map<String, Object> result = new HashMap<>();

        Map<String, String> maps = JsonUtils.parseObject(data, Map.class);
        String username = maps.get("username");
        String page_num = maps.get("page_num");
        String page_size = maps.get("page_size");

        PageInfo pageInfo = new PageInfo();
        pageInfo.setPageNum(Integer.valueOf(page_num));
        pageInfo.setPageSize(Integer.valueOf(page_size));
        List<Department> depts = new ArrayList<Department>();

        //查询orgType
        List<Org> orgs = departmentDao.selectHospitalCode(username);
        for (Org org : orgs) {
            Department department = new Department();
            department.setId(UUIDUtil.get32UUID());
            if(org.getOrgType() == 1 || org.getOrgType() == 2){
                department.setHospitalId(org.getId());
                department.setHospitalCode(org.getOrgCode());
                department.setHospitalName(org.getOrgName());
                department.setUpdateTime(org.getUpdateTime());
                depts.add(department);
            }else if(org.getOrgType() == 3){
                //查询该组织下扩展机构
                OrgAppDevelop orgAppDevelop = new OrgAppDevelop();
                orgAppDevelop.setOrgId(org.getId());
                List<OrgAppDevelop> orgAppDevelops = orgAppDevelopDao.select(orgAppDevelop);
                for (OrgAppDevelop appDevelop : orgAppDevelops) {
                    Department depart = new Department();
                    depart.setHospitalId(appDevelop.getDevOrgId());
                    depart.setHospitalName(appDevelop.getDevOrgName());
                    depart.setHospitalCode(appDevelop.getDevOrgCode());
                    depart.setUpdateTime(appDevelop.getUpdateTime());
                    depts.add(depart);
                }
            }
        }

        //去重
        HashSet hashSet = new HashSet(depts);
        depts.clear();
        depts.addAll(hashSet);

        pageInfo.setTotal(Long.valueOf(depts.size()));
        pageInfo.setPages((pageInfo.getTotal().intValue() + pageInfo.getPageSize() - 1) / pageInfo.getPageSize());
        //分页
        logger.info(">>>");
        if(depts.size() > 0){
            depts =  ListUtils.subLists(depts, pageInfo.getPageSize(), pageInfo.getPageNum());
        }
        result.put("list" , depts);
        result.put("page_info" , pageInfo);
        response.setResult(JsonUtils.toJsonString(result));
        response.setResultCodeAndMessage("0", "查询成功!");

        return response;

    }

    /**
     * 获取医院的支付参数 yyt.base.hospital.paysetting.get
     *
     * @param data
     * @param sessionid
     * @return
     */
    public Response getHospitalPaysetting(String data, String sessionid) {

        Response response = new Response();

        Map<String, String> maps = JsonUtils.parseObject(data, Map.class);
        String hospitalCode = maps.get("hospital_code");
        String appCode = maps.get("app_code");

        HospitalPaySetting wheres = new HospitalPaySetting();
        wheres.setCode(hospitalCode);
        wheres.setAppCode(appCode);
        List<HospitalPaySetting> hpays = hospitalDao.selectForPaySetting(wheres);

        response.setResultCodeAndMessage("0", "查询成功!");
        response.setResult(JsonUtils.toJsonString(hpays));

        return response;

    }
    
    /**
     * 查询医院的私匙，appId等信息
     * yyt.base.hospital.appinfo.get
     * @param data 
     * @param data
     * @param sessionid
     * @return
     */
    public HospitalCodeAndAppVo getHospitalAppInfo(String data, String sessionid) {
    	
    	JSONObject jsonObj = JsonUtils.parseObject(data);
    	if (StringUtils.isEmpty(jsonObj.getString("hospital_code")) || StringUtils.isEmpty(jsonObj.getString("app_code"))) {
    		return null;
    	}
    	
    	HospitalCodeAndAppVo vo = null;
    	String jsonStr = CacheService.getGlobalKey("base", "hospital_app", jsonObj.getString("hospital_code")+"_"+jsonObj.getString("app_code"));
    	
    	if (isValidCache(jsonStr)) {
    		vo = JsonUtils.parseObject(jsonStr, HospitalCodeAndAppVo.class);
    	}
    	else {
    		vo = hospitalDao.queryCodeAndApp(jsonObj.getString("hospital_code"),jsonObj.getString("appCode"));
        	if (vo != null) {
        		CacheService.setGlobalKey("base", "hospital_app", vo.getHospitalCode()+"_"+vo.getAppCode(), JsonUtils.toJsonString(vo),3600*24*7);
        	}
    	}
    	
    	return vo;
    }
    
    /**
     * 列出指定医院的消息平台
     * @param data
     * @param sessionid
     * @return 如果没有配置的关系信息，返回null
     */
    public HospitalPlatformRelate getHospitalMessagePlatform(String data, String sessionid) {
    	
    	JSONObject jsonObj = JsonUtils.parseObject(data);
    	if (StringUtils.isEmpty(jsonObj.getString("hospital_code")) || StringUtils.isEmpty(jsonObj.getString("platform_code"))) {
    		return null;
    	}
    	
    	HospitalPlatformRelate vo = null;
    	String jsonStr = CacheService.getGlobalKey("base", "hospital_platform_relate", jsonObj.getString("hospital_code")+"_"+jsonObj.getString("platform_code"));
    	
    	if (isValidCache(jsonStr)) {
    		vo = JsonUtils.parseObject(jsonStr, HospitalPlatformRelate.class);
    	}
    	else {
    		vo = hospitalPlatformRelateDao.getMessagePlatform(jsonObj.getString("hospital_code"),jsonObj.getString("platform_code"));
        	if (vo != null) {
        		CacheService.setGlobalKey("base", "hospital_platform_relate", vo.getHospitalCode()+"_"+vo.getPlatformCode(), JsonUtils.toJsonString(vo),3600*24*7);
        	}
    	}
    	
    	return vo;
    }
    
    /**
     * 根据app_code获得app_id
     * @param data
     * @param sessionid
     * @return
     */
    public Map getAppIdByCode(String data, String sessionid) {
    	JSONObject jsonObj = JsonUtils.parseObject(data);
    	return getAppIdByCode(jsonObj.getString("app_code"));
    }
    
    public Map getAppIdByCode(String appCode) {
    	    	
    	
    	return null;
    }
    
	/**
	 * 检查从cache里获取的字符串值是否有效
	 * @param strJson 从cache里获取的字符串值
	 */
	public static boolean isValidCache(String strJson) {
		if (StringUtils.isNotEmpty(strJson) && ! strJson.equalsIgnoreCase("nil")) {
			return true;
		}
		return false;
	}

    public static  void fenye(List list,int pagesize){

        int totalcount=list.size();
        int pagecount=0;
        int m=totalcount%pagesize;
        if  (m>0){
            pagecount=totalcount/pagesize+1;
        }else{
            pagecount=totalcount/pagesize;
        }

        for(int i=1;i<=pagecount;i++){
            if (m==0){
                List<Integer> subList= list.subList((i-1)*pagesize,pagesize*(i));
                System.out.println(subList);
            }else{
                if (i==pagecount){
                    List<Integer> subList= list.subList((i-1)*pagesize,totalcount);
                    System.out.println(subList);
                }else{
                    List<Integer> subList= list.subList((i-1)*pagesize,pagesize*(i));
                    System.out.println(subList);
                }


            }
        }

    }

    /**
     * 根据应用编码查询医院列表
     * yyt.base.org.by.platform.org.app.code.get --> yyt.base.hospital.by.app.code.list
     * @param data
     * @return
     */
    public Response listHospitalByAppCode(String data) {
        Response response = new Response();
        Map<String,Object>  map = JsonUtils.parseObject(data, Map.class);
        if(map == null || !map.containsKey("app_code")){
            response.setResultCodeAndMessage("1001","输入参数有误，app_code不能为空");
            return response;
        }
        String appCode = (String) map.get("app_code");

        String cacheValue = CacheService.getGlobalKeyHash(CacheConstant.CACHE_BASE_MODULE,CacheConstant.CACHE_HOSPITAL_REGION,
                CacheConstant.CACHE_HASH_KEY,appCode);
        if(StringUtils.isNotBlank(cacheValue)){
            logger.info("【yyt.base.hospital.by.app.code.list】，缓存命中，cacheValue=" + cacheValue);
            response.setResult(cacheValue);
            response.setResultCodeAndMessage("0", "查询成功,缓存命中!");
            return response;
        }
        //查询数据库，并更新缓存
        List<HospitalOutVo> hospitalList = listHospitalByAppCodeDao(appCode);
        if(!CollectionUtils.isEmpty(hospitalList)) {
            CacheService.setGlobalKeyHash(CacheConstant.CACHE_BASE_MODULE, CacheConstant.CACHE_HOSPITAL_REGION,
                    CacheConstant.CACHE_HASH_KEY, appCode, JsonUtils.toJsonString(hospitalList));

            response.setResult(JsonUtils.toJsonString(hospitalList));
        }
        response.setResultCodeAndMessage("0", "查询成功!");

        return response;

    }

    /**
     * 刷新应用对应的医院列表缓存，根据应用编码查询医院列表
     * yyt.base.hospital.cache.by.app.code.reload
     * @param data
     * @return
     */
    public Response reloadHospitalCacheByAppCode(String data) {
        Response response = new Response();
        Map<String,Object>  map = JsonUtils.parseObject(data, Map.class);
        if(map == null || !map.containsKey("app_code")){
            response.setResultCodeAndMessage("1001","输入参数有误，app_code不能为空");
            return response;
        }
        String appCode = (String) map.get("app_code");
        List<HospitalOutVo> hospitalList = listHospitalByAppCodeDao(appCode);
        if(!CollectionUtils.isEmpty(hospitalList)) {
            CacheService.setGlobalKeyHash(CacheConstant.CACHE_BASE_MODULE, CacheConstant.CACHE_HOSPITAL_REGION,
                    CacheConstant.CACHE_HASH_KEY, appCode, JsonUtils.toJsonString(hospitalList));
        }else{
            CacheService.delGlobalKeyHash(CacheConstant.CACHE_BASE_MODULE, CacheConstant.CACHE_HOSPITAL_REGION,
                    CacheConstant.CACHE_HASH_KEY, appCode);
        }
        response.setResult(JsonUtils.toJsonString(hospitalList));
        response.setResultCodeAndMessage("0", "查询成功!");
        return response;
    }

    /**
     * 根据应用编码查询医院列表,查数据库，内部调用
     * @param appCode
     * @return
     */
    private List<HospitalOutVo> listHospitalByAppCodeDao(String appCode){
        List<Org> orgs ;
        if("all".equals(appCode)){
            //查询全部医院
            Org allQuery = new Org();
            allQuery.setOrgType((short) 1);
            orgs = orgDao.select(allQuery);
        }else {
            orgs = orgDao.selectByPlatformOrgAppCode(appCode);
        }
        List<HospitalOutVo> hospitalList = new ArrayList<>();
        for (Org org : orgs) {
            HospitalOutVo hos = new HospitalOutVo();
            hos.setHospitalCode(org.getOrgCode());
            hos.setHospitalName(org.getOrgName());
            hos.setProvinceName(org.getProvinceName());
            hos.setCityName(org.getCityName());
            hos.setAreaName(org.getAreaName());
            hos.setAddress(org.getAddress());
            hos.setOldPlatformFlag(org.getOldPlatformFlag());
            hos.setAuthPlatformFlag(org.getAuthPlatformFlag());
            hos.setAppId(org.getAppId());
            hos.setShowOrders(org.getShowOrders());
            hos.setOldPlatformCode(org.getOldPlatformCode());//旧平台医院编码

            BranchHospital parent = new BranchHospital();
            parent.setOrgId(org.getId());
            parent.setOrgCode(org.getOrgCode());
            List<BranchHospital> branchHospitals = branchHospitalDao.select(parent);
            if (branchHospitals != null && branchHospitals.size() > 0) {
                List<BranchOutVo> branchOutVos = new ArrayList<>();
                for (BranchHospital subOrg : branchHospitals) {
                    BranchOutVo branch = new BranchOutVo();
                    branch.setBranchId(subOrg.getId());
                    branch.setBranchCode(subOrg.getBranchCode());
                    branch.setBranchName(subOrg.getBranchName());
                    branch.setAddress(subOrg.getAddress());
                    branchOutVos.add(branch);
                }
                hos.setBranchList(branchOutVos);
            }
            hospitalList.add(hos);
        }
        return hospitalList;
    }

    /**
     * 添加应用下医院  yyt.base.hospital.by.app.add
     * @param data app_code,org_code,show_orders
     * @return
     */
    public Response addHospitalByApp(String data) {
        Response response = new Response();
        Map<String,Object>  map = JsonUtils.parseObject(data, Map.class);
        if(map == null || !map.containsKey("app_code")){
            response.setResultCodeAndMessage("1001","输入参数有误，app_code不能为空");
            return response;
        }
        if(!map.containsKey("org_code") || StringUtils.isBlank((String)map.get("org_code"))){
            response.setResultCodeAndMessage("1001","输入参数有误，org_code不能为空");
            return response;
        }
        String appCode = (String) map.get("app_code");
        String orgCode = (String) map.get("org_code");

        OrgApp orgApp = BaseService.getBaseClient().getOrgAppByAppCode(appCode);
        if(orgApp == null){
            response.setResultCodeAndMessage("1005","应用不存在,appCode=" + appCode);
            return response;
        }

        Org org = BaseService.getBaseClient().getOrgByCode(orgCode);
        if(org == null){
            response.setResultCodeAndMessage("1005","机构不存在,orgCode=" + orgCode);
            return response;
        }
        OrgAppDevelop query = new OrgAppDevelop();

        query.setDevOrgCode(orgCode);
        query.setPlatformOrgAppCode(appCode);
        List<OrgAppDevelop> list = orgAppDevelopDao.select(query);
        OrgAppDevelop develop;
        if(list != null && list.size() > 0){
            //更新记录
            develop = list.get(0);
            develop.setOrgId(orgApp.getOrgId());
            develop.setOrgCode(orgApp.getOrgCode());
            develop.setOrgName(orgApp.getOrgName());
            develop.setPlatformId(orgApp.getOrgId());
            develop.setPlatformCode(orgApp.getOrgCode());
            develop.setPlatformName(orgApp.getOrgName());

            develop.setDevOrgId(org.getId());
            develop.setDevOrgCode(org.getOrgCode());
            develop.setDevOrgName(org.getOrgName());

            develop.setPlatformOrgAppCode(orgApp.getOrgAppCode());
            develop.setPlatformOrgAppName(orgApp.getOrgAppName());
            if(map.get("show_orders") != null){
                develop.setShowOrders(ObjectParser.toInteger(map.get("show_orders")));
            }
            orgAppDevelopDao.update(develop);
        }else {
            //新增记录
            develop = new OrgAppDevelop();
            develop.setId(PKGenerator.generateId());
            develop.setOrgId(orgApp.getOrgId());
            develop.setOrgCode(orgApp.getOrgCode());
            develop.setOrgName(orgApp.getOrgName());
            develop.setPlatformId(orgApp.getOrgId());
            develop.setPlatformCode(orgApp.getOrgCode());
            develop.setPlatformName(orgApp.getOrgName());

            develop.setDevOrgId(org.getId());
            develop.setDevOrgCode(org.getOrgCode());
            develop.setDevOrgName(org.getOrgName());

            develop.setPlatformOrgAppCode(orgApp.getOrgAppCode());
            develop.setPlatformOrgAppName(orgApp.getOrgAppName());
            if (map.get("show_orders") != null) {
                develop.setShowOrders(ObjectParser.toInteger(map.get("show_orders")));
            }
            orgAppDevelopDao.insert(develop);
        }
        reloadHospitalCacheByAppCode("{\"app_code\":\"" + appCode +"\"}");

        response.setResult(JsonUtils.toJsonString(develop));
        response.setResultCodeAndMessage("0", "查询成功!");

        return response;

    }

    /**
     *删除应用下医院  yyt.base.hospital.by.app.delete
     * @param data
     * @return
     */
    public Response deleteHospitalByApp(String data,String sessionId) {
        Response response = new Response();
        Map<String,Object>  map = JsonUtils.parseObject(data, Map.class);
        if(map == null || !map.containsKey("dev_org_code")){
            response.setResultCodeAndMessage("1001","输入参数有误，app_code不能为空");
            return response;
        }
        if(!map.containsKey("dev_org_code") || StringUtils.isBlank((String)map.get("dev_org_code"))){
            response.setResultCodeAndMessage("1001","输入参数有误，org_code不能为空");
            return response;
        }
        String appCode = (String) map.get("app_code");
        String devOrgCode = (String) map.get("dev_org_code");

        OrgAppDevelop develop = new OrgAppDevelop();
        develop.setPlatformOrgAppCode(appCode);
        develop.setDevOrgCode(devOrgCode);

        orgAppDevelopDao.deleteByAppCodeAndOrgCode(develop);

        reloadHospitalCacheByAppCode("{\"app_code\":\"" + appCode +"\"}");

        response.setResult(JsonUtils.toJsonString(develop));
        response.setResultCodeAndMessage("0", "删除成功!");

        return response;

    }

    public static void main(String[] args) {
        List<Integer> list=new ArrayList<Integer>();
        for(int i=1;i<52;i++){
            list.add(i);
        }

        fenye(list,10);

    }
}

